package com.runrun.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.runrun.io.resources;
import com.runrun.pojo.Configuration;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.swing.text.html.FormSubmitEvent;
import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class XMLConfigBuilder {
    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    //因为这是config配置文件解析类，所以返回值应为config对象(自己靠记忆，理解去写，这儿本意是要导入resources类获取inputstream
    // 但是看了源代码发现没有引入这个方法，疑惑在哪调用的，每个方法各自有各自的功能，先实现每个方法的功能，最后合的时候在修改吧)
    public Configuration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {
        //通过dom4j解析SqlConfigMapper.xml
        Document document = new SAXReader().read(inputStream);
        //获取根结点
        Element rootElement = document.getRootElement();
        //获取每个property节点
        List<Element> propertyList = rootElement.selectNodes("//property");
        Properties properties = new Properties();// todo 不是很理解这个是什么，看源码应该是类似与map的一个集合
        //遍历propertyList,获取每个property的值
        for (Element property : propertyList) {
            String name = property.attributeValue("name");
            String value = property.attributeValue("value");
            properties.setProperty(name, value);
        }
        //获取jdbc连接值
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        configuration.setDataSource(comboPooledDataSource);
        //下一步要解析UserMapper.xml里的内容
        //其实SqlConfigMapper内容目前来说只是分为两类：数据库信息，SqlMapper信息（有可能为多个）
        List<Element> mapperList = rootElement.selectNodes("//mapper");
        //遍历mapperList集合，
        for (Element elementMapper : mapperList) {
            XMLSqlMapperBuild xmlSqlMapperBuild = new XMLSqlMapperBuild(configuration);
            String resource = elementMapper.attributeValue("resource");
            InputStream resourcesAsInputStream = resources.getResourcesAsInputStream(resource);
            xmlSqlMapperBuild.parseSqlMapper(resourcesAsInputStream);
        }
        return configuration;
    }
}
